﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace AcServerWrapper
{
    public class RuleConfiguration
    {
        [XmlElement("RuleSet")]
        public List<RuleSet> RuleSets = new List<RuleSet>();

        public int Count
        {
            get
            {
                int cnt = 0;
                foreach (var rs in RuleSets)
                {
                    cnt += rs.Rules.Count;
                }
                return cnt;
            }
        }

        public static RuleConfiguration Deserialize(string filename)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(RuleConfiguration));
            using (TextReader reader = new StreamReader(filename))
                return deserializer.Deserialize(reader) as RuleConfiguration;
        }

        public void Serialize(string filename)
        {
            XmlSerializer x = new XmlSerializer(this.GetType());
            using (TextWriter writer = new System.IO.StreamWriter(filename))
            {
                x.Serialize(writer, this);
            }
        }

        internal string GetSection(string acLogLine)
        {
            // the task is: is there a rule that applies to this log line? 
            // If so, simply return the section name.
            foreach (var ruleset in RuleSets)
                foreach (var rule in ruleset.Rules)
                {
                    if (rule.DoesApplyTo(acLogLine))
                    {
                        return ruleset.Name;
                    }
                }

            // Nothing applied? then the section is "unknow"
            return "unknown";
        }
    }
}
